package com.cskaoyan.controller;

import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.basebean.BaseRespVo;
import com.cskaoyan.bean.basebean.BasePageData;
import com.cskaoyan.bean.GoodsToTopic;
import com.cskaoyan.bean.GoodsToTopicVo;
import com.cskaoyan.bean.Topic;
import com.cskaoyan.exception.GoodsToTopicException;
import com.cskaoyan.exception.TopicException;
import com.cskaoyan.service.GoodsToTopicService;
import com.cskaoyan.service.TopicService;
import org.apache.poi.hssf.record.DVALRecord;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lxy
 * @create 2021-10-18 19:00
 */
@RestController
@RequestMapping("admin/topic")
public class TopicController {

    @Autowired
    TopicService topicService;

    @RequiresPermissions(value = "admin:topic:list")
    @RequestMapping("list")
    public BaseRespVo list(String title, String subtitle, BaseParam baseParam) {
        BasePageData data = topicService.query(title, subtitle, baseParam);
        return BaseRespVo.ok(data);
    }

    @RequiresPermissions(value = "admin:topic:delete")
    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Topic topic) throws TopicException {
        topicService.deleteTopic(topic);
        return BaseRespVo.ok();
    }

    @RequiresPermissions("admin:topic:create")
    @RequestMapping("create")
    public BaseRespVo create(@RequestBody Topic topic) throws TopicException {
        topicService.createTopic(topic);
        return BaseRespVo.ok(topic);
    }

    @RequiresPermissions(value = "admin:topic:update")
    @RequestMapping("update")
    public BaseRespVo update(@RequestBody Topic topic) throws TopicException {
        topicService.updateTopic(topic);
        return BaseRespVo.ok(topic);
    }

    @Autowired
    GoodsToTopicService goodsToTopicService;

    @RequiresPermissions(value = "admin:topic:read")
    @RequestMapping("read")
    public BaseRespVo read(Integer id) throws TopicException, GoodsToTopicException {

        GoodsToTopicVo goodsToTopicVo = new GoodsToTopicVo();

        Topic topic = topicService.getReadTopic(id);

        Integer[] goods = topic.getGoods();

        List<GoodsToTopic> goodsToTopicList = new ArrayList<>();

        for (Integer goodsId : goods) {
            GoodsToTopic goodsToTopic = goodsToTopicService.getTopicGoods(goodsId);
            goodsToTopicList.add(goodsToTopic);
        }

        goodsToTopicVo.setGoodsList(goodsToTopicList);
        goodsToTopicVo.setTopic(topic);

        return BaseRespVo.ok(goodsToTopicVo);
    }
}
